﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Threading;
using System.Globalization;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace THS.Controllers
{
    public abstract class BaseController : Controller
    {
        protected override void ExecuteCore()
        {
            if (RouteData.Values["lang"] != null &&
                !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
            {
                // set the culture from the route data (url)
                var lang = RouteData.Values["lang"].ToString();
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
            }
            else
            {
                // load the culture info from the cookie
                var cookie = HttpContext.Request.Cookies["THS.CurrentUICulture"];
                var langHeader = string.Empty;
                if (cookie != null)
                {
                    // set the culture by the cookie content
                    langHeader = cookie.Value;
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
                }
                else
                {
                    // set the culture by the location if not speicified
                    langHeader = HttpContext.Request.UserLanguages[0];
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
                }
                // set the lang value into route data
                RouteData.Values["lang"] = langHeader;
            }

            // save the location into cookie
            HttpCookie _cookie = new HttpCookie("THS.CurrentUICulture", Thread.CurrentThread.CurrentUICulture.Name);
            _cookie.Expires = DateTime.Now.AddYears(1);
            HttpContext.Response.SetCookie(_cookie);

            base.ExecuteCore();
        }
         protected override RedirectResult Redirect(string url)
        {
            return new AjaxAwareRedirectResult(url);
        }
        public class AjaxAwareRedirectResult : RedirectResult
        {
            public AjaxAwareRedirectResult(string url)
                : base(url)
            {
            }

            public override void ExecuteResult(ControllerContext context)
            {
                if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);

                    JavaScriptResult result = new JavaScriptResult()
                    {
                        Script = "window.location='" + destinationUrl + "';"
                    };
                    result.ExecuteResult(context);
                }
                else
                    base.ExecuteResult(context);
            }
        }
        //public bool IsAuthenticateAdmin()
        //{
        //    if (Session["Admin"]==null)
        //        return false;
        //    int adminID = 0;
        //    Int32.TryParse(Session["Admin"].ToString(), out adminID);
        //    DBContainer ctx = new DBContainer();
        //    Models.Admin adm = ctx.Admins.SingleOrDefault(p => p.AdminID == adminID);

        //    if (adm.PCIP.Equals(GetCookie()))
        //        return true;
        //    return false;

        //}
        //public string GetCookie()
        //{
        //   return HttpContext.Request.ServerVariables["HTTP_COOKIE"];
        //}
        public static bool IsImageFile(string fileName)
        {
            FileInfo info = new FileInfo(fileName);
            string extention = info.Extension.ToLower();
            if (extention == ".jpg" || extention == ".gif" || extention == ".png")
                return true;
            else
                return false;
        }
        public static bool IsVideo(string fileName)
        {
            FileInfo info = new FileInfo(fileName);
            string extention = info.Extension.ToLower();
            if (extention == ".flv")
                return true;
            else
                return false;
        }
        // Delete file
        public static void DeleteFile(HttpRequestBase requestBase, String virtualPath, String fileName)
        {
            String Name = System.IO.Path.GetFileName(fileName);
            String virtualFullPath = virtualPath + "/" + Name;
            String filePath = Path.Combine(requestBase.MapPath(virtualFullPath));
            FileInfo info = new FileInfo(filePath);
            if (info.Exists)
                info.Delete();
        }
        public static String GenerateImageName(HttpRequestBase requestBase, String virtualPath, String fileName, String userID)
        {

            FileInfo fileInfo = new FileInfo(fileName);
            //get extension file
            String extension = fileInfo.Extension;
            //gen name with user id
            fileName = "Images" + userID;
            String sFileName = fileName + extension;
            int file_append = 0;
            while (System.IO.File.Exists(Path.Combine(requestBase.MapPath(virtualPath + "/" + sFileName))))
            {
                file_append++;
                sFileName = fileName + file_append.ToString() + extension;
            }
            return sFileName;
        }

        
        //resize image
        public static bool ResizeImage(string originalFile, string newFilePath, int newWidth, int newHeight,int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizePhoto = new Size(newWidth, newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, newFilePath, originalFile, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }

        public static bool MakeImagesAndThumbFile(string originalFile,string newPhotoPath, string thumbPath,int newWidth,int newHeight,int thumbWidth,int thumbHeight,int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizeThumb = new Size(thumbWidth, thumbHeight);  //thumbs are actually limited only by height
            ResizeAnImage(ref img, sizeThumb, thumbPath, originalFile, resizeQuanlityPercent);
            Size sizePhoto = new Size(newWidth,newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, newPhotoPath, originalFile, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }
        //
        private static bool ResizeAnImage(ref System.Drawing.Image img, Size sizeNew, string filePath, string strOriginalFile, int resizeQuanlityPercent)
        {
            int intOrigWidth = img.Width;
            int intOrigHeight = img.Height;
            int intNewWidth = sizeNew.Width;
            int intNewHeight = sizeNew.Height;
            if (intOrigWidth < intNewWidth && intOrigHeight < intNewHeight)
            {
                //image is smaller than resized should be, do nothing
                System.IO.File.Copy(strOriginalFile, filePath, true);
                return false;
            }
            else
            {
                float flWidth2Height = (float)intOrigWidth / (float)intOrigHeight;
                float flNewWidth2Height = (float)intNewWidth / (float)intNewHeight;
                if (flWidth2Height > flNewWidth2Height)
                {
                    //Horizontal, make height smaller then in spec
                    //Use width to calc the scale
                    float flScale = (float)intNewWidth / (float)intOrigWidth;
                    intNewHeight = System.Convert.ToInt32(flScale * intOrigHeight);
                }
                else
                {
                    //Vertical, make width smaller then in spec
                    //Use height to calc the scale
                    float flScale = (float)intNewHeight / (float)intOrigHeight;
                    intNewWidth = System.Convert.ToInt32(flScale * intOrigWidth);
                }
                //Make a bitmap for the result
                Image imgNew = new Bitmap(intNewWidth, intNewHeight, img.PixelFormat);
                //Make a Graphics object for the result Bitmap
                Graphics oGraphic = Graphics.FromImage(imgNew);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle(0, 0, intNewWidth, intNewHeight);
                oGraphic.DrawImage(img, oRectangle);

                // Encoder parameter for image quality (thanks Dmitry A. Mottl)
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)resizeQuanlityPercent);
                // Jpeg image codec
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                imgNew.Save(filePath, jpegCodec, encoderParams);

                //imgNew.Save(strFile, ImageFormat.Jpeg); 
                imgNew.Dispose();
                return true;
            }
        }
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
    }
}
